from django.views import View
from django import http
from django_redis import get_redis_connection
from logging import getLogger

from random import randint
from meiduo_mall.apps.libs.captcha.captcha import captcha
from meiduo_mall.utils.response_code import RETCODE
from . import constants
from celery_mall.sms.tasks import ccp_send_sms_code


#创建日志器，
logger = getLogger('django')

#图形验证
class ImageCodeView(View):
    '''图形验证'''

    def get(self, requset, uuid):
        name, text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex(uuid, constants.SMS_CODE_EXPIRE, text)

        return http.HttpResponse(image, content_type='image/jpg')

#短信验证
class SMSCodeView(View):
    '''短信验证'''

    def get(self, request, mobile):
        # 2.1 创建redis连接对象
        redis_conn = get_redis_connection('verify_codes')
        #先尝试获取该用户60S内是否发送过验证码
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code':RETCODE.THROTTLINGERR, 'errmsg':'发送短信过于频繁'})


        #1.接收
        query_dict = request.GET
        image_code_client = query_dict.get('verify_code')
        uuid = query_dict.get('uuid')

        #2.校验
        if all([image_code_client, uuid]) is False:
            return http.HttpResponseForbidden('缺少必传参数')

        #创建redis管道
        pl = redis_conn.pipeline()
        #获取redis中保存的图形验证码,没有返回None
        image_code_server_bytes = redis_conn.get(uuid)
        #将图形验证码设置成一次性的，即拿出来的同时马上从redis中删除该数据
        # redis_conn.delete(uuid)
        pl.delete(uuid)
        #2.2 判断redis中的图形验证码是否过期
        if image_code_server_bytes is None:
            return http.HttpResponseForbidden({'code':RETCODE.THROTTLINGERR, 'errmsg':'图形验证码已过期'})

        #2.3 将获取的图形验证码转成str类型
        image_code_server_bytes = image_code_server_bytes.decode()
        #2.4 判断redis中的图形验证码与客户输入的是否一致
        if image_code_server_bytes.lower() != image_code_client.lower():
            return http.HttpResponseForbidden({'code':RETCODE.THROTTLINGERR, 'errmsg':'验证码不一致'})

        #3.发短信
        #生成6位数的验证码
        sms_code = '%06d' % randint(0, 999999)
        logger.info(sms_code)
        #保存短信验证码
        # redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_EXPIRE, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_EXPIRE, sms_code)

        #发送短信验证码
        #CCP().send_template_sms('接收短信的手机号', [验证码, 提示用户的过期时间：单位分钟], 1)
        # CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_EXPIRE_SERVER], 1)
        #clerey异步发送短信验证码
        ccp_send_sms_code.delay(mobile, sms_code)
        #往redis中存入该客户60s内已发送数据的信息，避免其频繁发送短信
        # redis_conn.setex('send_flag_%s' % mobile, constants.END_FLAG_MODILE, 短信模板编号)
        pl.setex('send_flag_%s' % mobile, constants.END_FLAG_MODILE, 1)
        #执行管道命令
        pl.setex()


        # 响应结果
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '发送短信成功'})
